package com.meatball.authorization.controller

import com.meatball.authorization.data.dto.CreateRoleParams
import com.meatball.authorization.data.dto.UpdateRoleParams
import com.meatball.authorization.data.entity.RoleEntity
import com.meatball.authorization.service.RoleService
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.Parameters
import io.swagger.v3.oas.annotations.enums.ParameterIn
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.util.*

/**
 * TODO 角色管理控制层
 *
 * @property roleService
 *
 * @author 张翔宇
 * @since 2024年3月28日
 */
@Tag(name = "角色")
@RestController
@RequestMapping("/role")
class RoleController (private val roleService: RoleService) {
    @Operation(summary = "新增角色")
    @PostMapping
    @PreAuthorize("hasAnyRole(@roleHandler.roles())")
    fun create(@RequestBody @Validated role: CreateRoleParams) {
        roleService.create(role)
    }

    @Operation(summary = "查询所有角色")
    @GetMapping("/read-all")
    @PreAuthorize("hasAnyRole(@roleHandler.roles())")
    fun readAll(): Iterable<RoleEntity> {
        return roleService.readAll()
    }

    @Operation(summary = "根据ID查询角色信息")
    @Parameters(
        Parameter(name = "id", description = "角色ID", `in` = ParameterIn.PATH, example = "1773177147784040448")
    )
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole(@roleHandler.roles())")
    fun readById(@PathVariable id: Long): Optional<RoleEntity> {
        return roleService.readById(id)
    }

    @Operation(summary = "修改角色信息")
    @Parameters(
        Parameter(name = "id", description = "角色ID", `in` = ParameterIn.PATH, example = "1773177147784040448")
    )
    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole(@roleHandler.roles())")
    fun update(@PathVariable id: Long, @RequestBody @Validated role: UpdateRoleParams) {
        return roleService.update(id, role)
    }

    @Operation(summary = "删除角色")
    @Parameters(
        Parameter(name = "id", description = "角色ID", `in` = ParameterIn.PATH, example = "1773177147784040448")
    )
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole(@roleHandler.roles())")
    fun delete(@PathVariable id: Long) {
        roleService.delete(id)
    }
}